//
//  EmotionViewController.swift
//  emojiKeyboardDemo
//
//  Created by Jin on 2018/5/16.
//  Copyright © 2018年 Jin. All rights reserved.
//

import UIKit

private let EmojiCellId = "emojiCell"

class EmotionViewController: UIViewController {

    private lazy var collectionView:UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: EmotionCollectionViewLayout())
    private lazy var toolBar:UIToolbar = UIToolbar()
    private lazy var manager = EmotionManager()
    
    var emotionCallBack : ((_ emotion:Emotion)->Void)?
    
    //自定义构造函数,必须super父类super.init(nibName: nil, bundle: nil)
    init(emotionCallBack:@escaping (_ emotion:Emotion)->Void) {
        super.init(nibName: nil, bundle: nil)
        self.emotionCallBack = emotionCallBack
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
}

extension EmotionViewController {
    private func setupUI() {
        view.addSubview(collectionView)
        view.addSubview(toolBar)
        collectionView.backgroundColor = UIColor.gray
        toolBar.backgroundColor = UIColor.green
        
        //设置子控件约束
        //纯代码设置AutoLayout需要将translatesAutoresizingMaskIntoConstraints设置为false
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        
        //VFL
        let views = ["toolBar":toolBar,"collectionView":collectionView]
        var cons = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[toolBar]-0-|", options: [], metrics: nil, views: views)
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[collectionView]-0-[toolBar]-0-|", options: [.alignAllLeft,.alignAllRight], metrics: nil, views: views)
        view.addConstraints(cons)
        
        //准备collectionView
        prepareForCollectionView()
        //准备toolBar
        prepareForToolBar()
    }
    
    private func prepareForCollectionView(){
        //注册collectionViewCell和设置数据源
        collectionView.register(EmotionCollectionViewCell.self, forCellWithReuseIdentifier: EmojiCellId)
        collectionView.dataSource = self as UICollectionViewDataSource
        collectionView.delegate = self as UICollectionViewDelegate

    }
    
    private func prepareForToolBar(){
        let titles = ["最近","默认","emoji","浪小花"]
        
        var index = 0
        var tempItems = [UIBarButtonItem]()
        for title in titles {
            let item = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(itemClick(item:)))
            item.tag = index
            index += 1
            tempItems.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
            tempItems.append(item)
        }
        tempItems.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        toolBar.items = tempItems
        toolBar.tintColor = UIColor.orange
    }
    
    @objc private func itemClick(item:UIBarButtonItem){
        let indexPath = IndexPath(item: 0, section: item.tag)
        collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
    }
}

extension EmotionViewController:UICollectionViewDataSource {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return manager.packages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let package = manager.packages[section]
        return package.emotions.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmojiCellId, for: indexPath) as! EmotionCollectionViewCell
        //cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.blue : UIColor.orange
        let package = manager.packages[indexPath.section]
        let emotion = package.emotions[indexPath.row]
        cell.emotion = emotion
        return cell
    }
}

extension EmotionViewController:UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let package = manager.packages[indexPath.section]
        let emotion = package.emotions[indexPath.item]
        insertRecentlyEmotion(emotion: emotion)
        emotionCallBack?(emotion)
    }
    
    private func insertRecentlyEmotion(emotion:Emotion){
        //如果是空白表情或删除不需要插入
        if emotion.isRemove || emotion.isEmpty {
            return
        }
        
        //删除一个表情
        if (manager.packages.first?.emotions.contains(emotion))! {
            //原来包含该表情
            let index = manager.packages.first?.emotions.index(of: emotion)
            manager.packages.first?.emotions.remove(at: index!)
        }else{
            //原来没有
            manager.packages.first?.emotions.remove(at: 19)
        }
        
        manager.packages.first?.emotions.insert(emotion, at: 0)
    }
}

class EmotionCollectionViewLayout: UICollectionViewFlowLayout {
    override func prepare() {
        super.prepare()
        
        let itemWH = UIScreen.main.bounds.width / 7
        itemSize = CGSize(width: itemWH, height: itemWH)
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = .horizontal
        
        //设置collectionView属性
        collectionView?.isPagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.showsVerticalScrollIndicator = false
    }
}
